import {$request} from '../../lib/page.auth'

const {regeneratorRuntime} = global;

let api = require('../../utils/api.js');
let http = require('../../utils/http.js');
let util = require('../../utils/util.js');
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        order_status: ['', '待支付', '等待接单', '等待开始', '陪玩中', '等待验收', '待评价', '已评价', '已取消', '已取消'],
        hour: 0,
        minute: 0,
        second: 0,
        order: {},
        timer: 0,
      boss_status: ['取消订单', '待支付', '提醒接单', '提醒开始', '陪玩中', '确认完成', '立即评价', '已评价', '已取消', '已取消'],
      player_status: ['', '待支付', '确认接单', '确认开始', '提交验收', '等待验收', '待评价', '已评价', '已取消'],
      opunit: api.opunit,
    },
    /* 支付失败或取消后的支付 */
    async payOrder(e) 
    {
        var order_id = e.currentTarget.dataset.order_id;
        var token = wx.getStorageSync('token');
        http.post(api.order_pay, {token:token,id: order_id}, function(res)
        {
            var result = res.data.data;
            if (res.data.code == 1) 
            {
                //支付成功跳转
                wx.navigateTo({
                    url: '/pages/mineOrderDetail/mineOrderDetail?id=' + order_id,
                })
            }
            else
            {
                //支付失败处理
                wx.showModal({
                    title: '支付失败',
                    showCancel: false,
                    content: result,
                    success: function (res) {
                        // wx.navigateTo({
                        //     // url: '/pages/indexPay/indexPay',
                        //     url: '/pages/mineOrderDetail/mineOrderDetail?id=' + order_id,
                        // })
                    }
                })
            }
        });

        // var order_id = e.currentTarget.dataset.order_id;
        // const res = await $request({url: api.order_pay, data: {id: order_id}, method: 'POST'});
        // let data = JSON.parse(res.data);
        // console.log('订单支付打印信息：', data);

        // wx.requestPayment({
        //     "timeStamp": data.timeStamp,
        //     "nonceStr": data.nonceStr,
        //     "package": data.package,
        //     "signType": data.signType,
        //     "paySign": data.paySign,
        //     "success": function (res) {
        //         wx.navigateTo({
        //             url: '/pages/mineOrderDetail/mineOrderDetail?id=' + order_id,
        //         })
        //     },
        //     "fail": function (res) {
        //         wx.showModal({
        //             title: '支付失败',
        //             showCancel: false,
        //             content: '支付出现一些问题，请尝试重新支付',
        //             success: function (res) {
        //                 wx.navigateTo({
        //                     url: '/pages/mineOrderDetail/mineOrderDetail?id=' + order_id,
        //                 })
        //             }
        //         })
        //     }
        // });
    },
  /* =================================陪玩师操作 =================================*/
  async playerOpHandler(e) {
    let formId = e.detail.formId;
    await util.getFormIds(formId);

    let dataset = e.currentTarget.dataset;
    console.log(dataset);
    switch (dataset.status) {
      case 2:
        this.confirmTap(e);//确认接单：
        break;
      case 3:
        this.playStartTap(e);//确认开始
        break;
      case 4:
        this.confirmFinishTap(e);//游戏结束，提交验收
        break;
    }
  },
  confirmTap: function (e) {
    var token = wx.getStorageSync('token');
    var that = this;
    wx.showModal({
      title: '提醒',
      content: '确认接受接单吗?',
      success: function (res) {
        console.log(res.confirm);
        if (res.confirm) {
          console.log(res.confirm);
          let res2 = that.confirmOrder().then(res => {
            console.log(res);
            if (res.code) {
              //发送推送消息
              $request({
                url: api.send_template_message,
                method: 'POST',
                data: {
                  templateId: api.messageTemplates.SUCCESS_IMFORM,
                  orderId: that.data.id,
                  token: token,
                }
              });

              wx.showModal({
                title: '提醒',
                content: '接单成功',
                confirmText: '确认开始',
                success: function (res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/mineOrderStart/mineOrderStart?id=' + that.data.id + '&uid=' + that.data.uid,
                    })
                  } else {
                    wx.navigateTo({
                      url: '/pages/mineOrder/mineOrder?uid=' + that.data.uid,
                    })
                  }
                }
              });

            } else {
              wx.showModal({
                title: '提醒',
                content: res.msg
              });
            }
          });
        }
      },
    })
  },
  async confirmOrder() {
    var token = wx.getStorageSync('token');
    var res = await $request({
      url: api.order_status_change,
      data: { id: this.data.id, status: 3, token: token },
      method: 'POST'
    });
    return res;
  },
  playStartTap: function (e) {
    var that = this;
    wx.showModal({
      title: '提醒',
      content: '确认开始吗?',
      success: function (res) {
        console.log(res.confirm);
        if (res.confirm) {
          let res2 = that.startOrder().then(res => {
            console.log(res);
            if (res.code) {
              wx.showToast({
                title: '已经确认开始',
                icon: 'none',
              });
              wx.navigateTo({
                url: '/pages/mineOrder/mineOrder?uid=' + that.data.uid,
              })
            } else {
              wx.showModal({
                title: '提醒',
                content: '操作失败，尝试刷新后重新接单'
              });
            }
          });
          // wx.navigateTo({
          //     url: '/pages/playConfirmOver/playConfirmOver',
          // })
        }
      },
    })
  },
  confirmFinishTap: function (e) {
    let dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/mineOrderAccep/mineOrderAccep?id=' + dataset.oid + '&uid=' + this.data.uid,
    })
  },
  confirmTakeTap:function(){
    console.log(2212121212);
    wx.navigateTo({
      url: '/pages/mineOrder/mineOrder',
    })
  },
  async startOrder() {
    var token = wx.getStorageSync('token');
    var res = await $request({
      url: api.order_status_change,
      data: { id: this.data.id, status: 4, token: token },
      method: 'POST'
    });
    return res;
  },
    clipboardTap: function () {
        wx.setClipboardData({
            data: this.data.order.contact,
        })
    },
    getOrderDetail() 
    {
        var that = this;
        var token = wx.getStorageSync('token');
        http.get(api.order_detail, {token:token,id: that.data.id}, function(res)
        {
            var result = res.data;
            console.log(res, '==========')
            if (res.data.code == 1) 
            {
                return result;
            }
            else
            {
                util.msg("请求接口失败！");
            }
        });
        // var res = await $request({
        //     url: api.order_detail,
        //     method: 'POST',
        //     data: {id: this.data.id}
        // });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) 
    {
        this.setData({id: options.id,uid:wx.getStorageSync("user_info").data.id});
        var hour = this.data.hour,
            minute = this.data.minute,
            second = this.data.second;
        var that = this;
        var token = wx.getStorageSync('token');

        http.get(api.order_detail, {token:token,id: that.data.id}, function(res)
        {
            var result = res.data;
            if (res.data.code == 1) 
            {
                let order = result.data;

                /* 根据剩余时间设定倒计时 */
                if (order.hasOwnProperty('remain_time')) {
                    var remainTime = order.remain_time;
                    minute = parseInt(remainTime / 60);
                    second = remainTime % 60;
                    console.log('剩下的时间：' + minute + "分" + second + "秒");
                    var timer = setInterval(function () {
                        if (second > 0) {
                            second--;
                        } else if (second == 0 && minute > 0) {
                            minute--;
                            second = 59;
                        } else if (second == 0 && minute == 0 && hour > 0) {
                            hour--;
                            minute = 59;
                            second = 59;
                        } else {
                            clearInterval(that.data.timer);
                          var order = that.data.order;
                          if (order.status<2){
                            wx.showToast({
                              icon: 'none',
                              title: '订单已自动取消',
                            });
                            }
                            
                            
                            order.cancelable = false;
                            if (order.status == 1) {
                                order.status = 8;
                                // var pages = getCurrentPages(); // 当前页面
                                // var beforePage = pages[pages.length - 2]; // 前一个页面
                                // beforePage.asyncOrderStatus(order.status);
                            }
                            that.setData({order: order});
                        }
                        that.setData({
                            hour: hour,
                            minute: minute,
                            second: second
                        })
                    }, 1000);
                    that.setData({timer: timer});
                }

                var token = wx.getStorageSync('token');
                http.get(api.user_info, {token:token}, function(res)
                {
                    if (res.data.code == 1) 
                    {
                        that.setData({
                            order: order,
                            user: res.data.data
                        });
                    }
                }, "请求中...");
            }
            else
            {
                util.msg("请求接口失败！");
            }
        });
        
        // console.log('订单详情');
        // console.log(order);
        // this.setData({
        //     order: order,
        //     user: app.globalData.user
        // });
    },
  async bossOpHandler(e) {
    let formId = e.detail.formId;
    await util.getFormIds(formId);

    let dataset = e.currentTarget.dataset;
    console.log(e);
    switch (dataset.status) {
      case "0":
        this.cancelOrder(e);
        break;
      case 1:
        this.topayTap(e); //支付
        break;
      case 2:
        this.remindOrder(e); //提醒接单
        break;
      case 3:
        this.remindStartTap(e);//提醒开始
        break;
      case 5:
        this.confirmOrder(e);//确认完成
        break;
      case 6:
        this.commentOrder(e);//立即评价
        break;
    }
  },
  //取消订单
  async cancelOrder(e) {
    var that = this;
    var cancel = false;
    wx.showModal({
      title: '提示',
      content: '取消订单操作不可更改，谨慎操作。确定取消吗?',
      async success(res) {
        if (res.cancel) {
          return;
        }
        var dataset = e.currentTarget.dataset;
        var token = wx.getStorageSync('token');
        http.get(api.order_cancel, { order_id: dataset.oid, token: token }, function (res) {
          console.log(res);
          var result = res.data;
          if (res.data.code == 1) {
            var order = that.data.order;
            order.cancelable = false;
            that.setData({ order: order });
            wx.showToast({
              icon: 'none',
              title: result.msg,
            });
          }
        });
        // var res = await $request({
        //     url: api.order_cancel,
        //     data: {order_id: dataset.oid},
        //     method: 'POST'
        // });
        // console.log(res);
        // var order = that.data.currentOrderList[dataset.index];
        // order.status = res.data;
        // order.cancelable = false;
        // that.data.currentOrderList[dataset.index] = order;
        // that.setData({currentOrderList: that.data.currentOrderList});
        // wx.showToast({
        //     icon: 'none',
        //     title: res.msg,
        // });
      }
    });
  },
    /* 订单状态改变时刷新页面 */
    async refreshPage() {
        var res = await this.getOrderDetail();
        this.setData({order: JSON.parse(res.data)});
        console.log(JSON.parse(res.data));
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.data.timer);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})